<template>
  <div class="math-problem-generator">
    <div class="container">
      <h2>数学题生成器</h2>
      
      <div class="settings">
        <div class="setting-item">
          <span class="label">题目范围:</span>
          <el-select v-model="numberRange" placeholder="请选择数字范围">
            <el-option 
              v-for="n in 20" 
              :key="n"
              :label="`${n * 10}以内`"
              :value="(n * 10).toString()">
            </el-option>
          </el-select>
        </div>

        <div class="setting-item">
          <span class="label">运算类型:</span>
          <el-button-group>
            <el-button :type="selectedType === 'add' ? 'primary' : ''" @click="selectedType = 'add'">加法</el-button>
            <el-button :type="selectedType === 'subtract' ? 'primary' : ''" @click="selectedType = 'subtract'">减法</el-button>
            <el-button :type="selectedType === 'multiply' ? 'primary' : ''" @click="selectedType = 'multiply'">乘法</el-button>
            <el-button :type="selectedType === 'divide' ? 'primary' : ''" @click="selectedType = 'divide'">除法</el-button>
          </el-button-group>
        </div>

        <div class="setting-item">
          <span class="label">题目数量:</span>
          <el-select v-model="problemCount" placeholder="请选择题目数量">
            <el-option 
              v-for="n in 20" 
              :key="n"
              :label="`${n * 10}道`"
              :value="(n * 10).toString()">
            </el-option>
          </el-select>
        </div>

        <div class="setting-item">
          <span class="label">显示答案:</span>
          <el-switch v-model="showAnswers"></el-switch>
        </div>
      </div>

      <div class="actions">
        <div class="button-group">
          <el-button type="primary" @click="generateProblems">生成题目</el-button>
          <el-button type="success" @click="printProblems" :disabled="!problems.length">打印题目</el-button>
          <el-button @click="goHome">返回首页</el-button>
        </div>
      </div>

      <div class="help-text">
        <h3>帮助说明：</h3>
        <div class="help-content">
          <p class="help-item">1. 选择题目范围（10-200以内）</p>
          <p class="help-item">2. 选择运算类型（加减乘除）</p>
          <p class="help-item">3. 选择题目数量（10-200道）</p>
          <p class="help-item">4. 可选择是否显示答案</p>
          <p class="help-item">5. 点击生成题目后可打印（一页A4纸）</p>
        </div>
      </div>

      <div class="problems-grid" ref="problemsGrid">
        <div v-for="(problem, index) in problems" :key="index" class="problem-item">
          <span>{{ problem.expression }} = </span>
          <span v-if="showAnswers">{{ problem.answer }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

const numberRange = ref('100')
const selectedType = ref('add')
const problemCount = ref('100')
const showAnswers = ref(false)
const problems = ref([])

const generateProblems = () => {
  problems.value = []
  const count = parseInt(problemCount.value)
  const range = parseInt(numberRange.value)

  for (let i = 0; i < count; i++) {
    let num1, num2, expression, answer

    switch (selectedType.value) {
      case 'add':
        num1 = Math.floor(Math.random() * (range - 1)) + 1  // 1 到 range-1
        num2 = Math.floor(Math.random() * (range - num1)) + 1  // 1 到 (range-num1)
        expression = `${num1} + ${num2}`
        answer = num1 + num2
        break
      case 'subtract':
        num2 = Math.floor(Math.random() * (range - 1)) + 1  // 1 到 range-1
        num1 = Math.floor(Math.random() * (range - num2)) + num2  // num2 到 range
        expression = `${num1} - ${num2}`
        answer = num1 - num2
        break
      case 'multiply':
        num1 = Math.floor(Math.random() * (Math.sqrt(range) - 1)) + 1  // 1 到 sqrt(range)
        num2 = Math.floor(Math.random() * (Math.sqrt(range) - 1)) + 1
        expression = `${num1} × ${num2}`
        answer = num1 * num2
        break
      case 'divide':
        num2 = Math.floor(Math.random() * (Math.sqrt(range) - 1)) + 1  // 1 到 sqrt(range)
        answer = Math.floor(Math.random() * (Math.sqrt(range) - 1)) + 1  // 1 到 sqrt(range)
        num1 = num2 * answer
        expression = `${num1} ÷ ${num2}`
        break
    }

    problems.value.push({
      expression,
      answer: answer.toString()
    })
  }
}

const printProblems = () => {
  if (!problems.value.length) {
    ElMessage.warning('请先生成题目再打印')
    return
  }
  
  requestAnimationFrame(() => {
    const printFrame = document.createElement('iframe')
    printFrame.style.cssText = 'position:absolute;top:-9999px;'
    document.body.appendChild(printFrame)
    
    // 取当前时间
    const now = new Date()
    const dateStr = `${now.getFullYear()}/${now.getMonth() + 1}/${now.getDate()} ${now.getHours()}:${String(now.getMinutes()).padStart(2, '0')}`

    // 根据运算类型生成标题
    let titleText = ''
    switch (selectedType.value) {
      case 'add':
        titleText = '100以内加法练习题'
        break
      case 'subtract':
        titleText = '100以内减法练习题'
        break
      case 'multiply':
        titleText = '100以内乘法练习题'
        break
      case 'divide':
        titleText = '100以内除法练习题'
        break
    }

    // 预先构建内容字符串
    const contentArray = []
    for (const problem of problems.value) {
      contentArray.push(`<div class="problem-cell">${problem.expression} = ${showAnswers.value ? problem.answer : ''}</div>`)
    }
    const content = contentArray.join('')

    const doc = printFrame.contentWindow.document
    const docFrag = doc.createDocumentFragment()
    
    const style = doc.createElement('style')
    style.textContent = `
      @media print {
        @page { 
          size: A4;
          margin: 0.15cm;
        }
        body { 
          font-family: Arial;
          padding: 0 15px;
          margin: 0;
          position: relative;
          height: 100vh;
          display: flex;
          flex-direction: column;
        }
        .header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 2px 5px;
          flex: none;
          height: 25px;
        }
        .date { 
          font-size: 12px; 
          color: #666;
        }
        .title { 
          font-size: 14px; 
          font-weight: bold;
          color: #333;
          text-align: center;
        }
        .problems {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          flex: 1;
          width: 100%;
          border: 1px solid #000;
          border-bottom: none;
          border-right: none;
          margin: 3px 0;
        }
        .problem-cell {
          padding: 0 10px;
          font-size: 22px;
          border-right: 1px solid #000;
          border-bottom: 1px solid #000;
          text-align: left;
          height: 42px;
          line-height: 42px;
          font-weight: 500;
          display: flex;
          align-items: center;
          box-sizing: border-box;
        }
        .footer {
          position: fixed;
          bottom: 2px;
          left: 0;
          width: 100%;
          display: flex;
          justify-content: space-between;
          padding: 0 20px;
          font-size: 10px;
          color: #666;
          height: 15px;
          flex: none;
        }
      }
    `
    docFrag.appendChild(style)

    const container = doc.createElement('div')
    container.innerHTML = `
      <div class="header">
        <div class="date">${dateStr}</div>
        <div class="title">${titleText}</div>
        <div style="width:80px"></div>
      </div>
      <div class="problems">${content}</div>
      <div class="footer">
        <span>www.xiyueta.com</span>
        <span>1/1</span>
      </div>
    `
    docFrag.appendChild(container)

    doc.write('<!DOCTYPE html><html><head></head><body></body></html>')
    doc.close()
    doc.body.appendChild(docFrag)

    const printPromise = new Promise(resolve => {
      printFrame.onload = () => {
        printFrame.contentWindow.focus()
        printFrame.contentWindow.print()
        resolve()
      }
    })

    printPromise.then(() => {
      setTimeout(() => {
        document.body.removeChild(printFrame)
      }, 100)
    })
  })
}

const goHome = () => {
  router.push('/')
}
</script>

<style lang="scss" scoped>
.math-problem-generator {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;

  h2 {
    text-align: center;
    color: #333;
    margin-bottom: 30px;
  }

  .settings {
    background: #f5f7fa;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;

    .setting-item {
      display: flex;
      align-items: center;
      margin-bottom: 15px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        width: 100px;
        color: #606266;
      }
    }
  }

  .actions {
    text-align: center;
    margin: 20px 0;
    padding: 0 15px;

    .button-group {
      display: flex;
      gap: 15px;
      justify-content: center;
      
      @media screen and (max-width: 768px) {
        flex-direction: column;
        width: 100%;
        gap: 10px;
        
        .el-button {
          margin: 0;
          width: 100%;
          height: 40px;
          display: flex;
          align-items: center;
          justify-content: center;
          
          & + .el-button {
            margin-left: 0;
          }
        }
      }
    }
  }

  .help-text {
    background: #f8fafc;
    padding: 20px 25px;
    border-radius: 12px;
    margin-bottom: 30px;
    border-left: 4px solid #409eff;
    text-align: left;

    h3 {
      color: #2c3e50;
      margin: 0 0 15px 0;
      font-size: 18px;
      font-weight: 600;
    }

    .help-content {
      padding-left: 0;

      .help-item {
        color: #666;
        margin: 0 0 8px 0;
        line-height: 1.8;
        font-size: 14px;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  .problems-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 15px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

    .problem-item {
      padding: 10px;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      text-align: center;
      
      span {
        font-size: 16px;
        color: #303133;
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .math-problem-generator {
    padding: 10px;

    .settings {
      padding: 15px 10px;

      .setting-item {
        flex-direction: column;
        align-items: flex-start;
        width: 100%;

        .label {
          margin-bottom: 5px;
          width: auto;
        }

        .el-select,
        .el-button-group {
          width: 100%;
        }
      }
    }

    .problems-grid {
      grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
      gap: 10px;
      padding: 10px;
      margin: 0 10px;
    }

    .help-text {
      padding: 15px 20px;
      margin: 20px 10px;

      h3 {
        font-size: 16px;
        margin-bottom: 12px;
      }

      .help-content {
        .help-item {
          font-size: 13px;
          margin-bottom: 6px;
        }
      }
    }
  }
}
</style> 